<template>
  <div>
    <div v-if="isAdmin" class="filter-container" style="height: 60px;">
      <span class="filter-container-right">
        <el-button type="primary" size="medium" icon="el-icon-plus" @click="addCustomGroup">新增</el-button>
        <el-button type="danger" size="medium" icon="el-icon-close" @click="delCustomGroups">删除</el-button>
      </span>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      row-key="id"
      fit
      border
      highlight-current-row
      style="width: 100%"
      @selection-change="handleSelectChange">
      <el-table-column type="selection" width="40"/>
      <el-table-column align="center" label="ID" width="65">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="130px" label="组名">
        <template slot-scope="scope">
          <span>{{ scope.row.group_name }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="创建人" min-width="130">
        <template slot-scope="scope">
          <span>{{ scope.row.create_user }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否公共组" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.is_public === 0 ? '否' : '是' }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="180" align="center" label="描述">
        <template slot-scope="scope">
          <span>{{ scope.row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="isAdmin" min-width="80" align="center" label="拖拽">
        <template slot-scope="scope">
          <svg-icon class="drag-handler" icon-class="drag"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="320">
        <template slot-scope="scope">
          <el-button v-if="isAdmin" type="primary" size="mini" icon="el-icon-edit" @click="editCustormGroup(scope.row)">修改</el-button>
          <el-button v-if="isAdmin" type="danger" size="mini" icon="el-icon-delete" @click="delCustomGroup(scope.row)">删除</el-button>
          <el-button type="success" size="mini" icon="el-icon-user" @click="usersChange(scope.row)">组员</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title=" isEdit ? '编辑自定义组' : '新增自定义组'" :visible.sync="FormVisible" width="600px">
      <el-form ref="ruleForm" :model="custormGroupForm" :rules="rules" >
        <el-form-item :label-width="formLabelWidth" label="自定义组名称" prop="group_name">
          <el-input v-model="custormGroupForm.group_name" auto-complete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="自定义组描述" prop="description">
          <el-input v-model="custormGroupForm.description" type="textarea" auto-complete="off"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd()">取 消</el-button>
        <el-button type="primary" @click="isEdit ? confirmEditCustormGroup('ruleForm') : confirmAddCustomGroup('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormVisible" title="修改参与者" width="600px" @close="cancel">
      <div style="margin-bottom: 20px" class="drag-participants">
        <el-tag v-for="item in participants" :key="item.id" closable type="primary" class="user-tag" @close="tagClose(item)">
          {{ item.realName }}
        </el-tag>
      </div>
      <el-select
        v-model="customGroupUsersChange.users"
        :remote-method="getCustomGroupUsers"
        :loading="loading"
        style="width:550px"
        multiple
        filterable
        remote
        reserve-keyword
        placeholder="参与者部门搜索">
        <el-option
          v-for="item in users"
          :key="item.id"
          :label="item.real_name"
          :value="item.id"/>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button v-if="isAdmin" type="primary" @click="confirmUsersChange()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import commonApi from '@/api/commonApi'
import Sortable from 'sortablejs'

export default {
  name: 'CommonCustomGroupList',
  props: {
    isAdmin: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      sortable: null,
      sortableParticipant: null,
      oldList: [],
      newList: [],
      dialogFormVisible: false,
      loading: false,
      FormVisible: false,
      isEdit: false,
      users: null,
      rules: {
        group_name: [
          { required: true, message: '请输入自定义组名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入自定义组描述', trigger: 'blur' }
        ]
      },
      delCustomGroupIds: [],
      formLabelWidth: '120px',
      searchObj: {
        currentNo: 1,
        pageSize: 10,
        data: {
          beginTime: null,
          endTime: null,
          username: null
        }
      },
      searchUsers: {
        currentNo: 1,
        pageSize: 1000,
        data: {
          username: null,
          real_name: null,
          department: null
        }
      },
      custormGroupForm: {},
      copycustormGroupForm: {}, // 修改取消时使用
      customGroupUsersChange: {
        group_id: null,
        users: []
      },
      participants: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      commonApi('/userGroup/queryPublicGroup', 'get').then(response => {
        this.list = response.data
        this.listLoading = false
        this.oldList = this.list.map(v => v.id)
        this.newList = this.oldList.slice()
        this.$nextTick(() => {
          this.setSort()
        })
      })
    },
    setSort() {
      const el = document.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          dataTransfer.setData('Text', '')
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
        },
        onEnd: evt => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)

          // for show the changes, you can delete in you code
          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)

          this.dataSortChange(this.newList)
        }
      })
    },
    dataSortChange(newList) {
      commonApi('/userGroup/sort', 'post', newList).then(response => {
        if (response.code === 1) {
          console.log('排序完成')
        }
      })
    },
    addCustomGroup() {
      this.isEdit = false
      this.FormVisible = true
    },
    confirmAddCustomGroup(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.FormVisible = false
          this.listLoading = true
          commonApi('/userGroup/addUserGroup', 'post', { group: this.custormGroupForm }).then(response => {
            if (response.code === 1) {
              this.cancelAdd()
              this.listLoading = false
              this.getList()
            }
          }).catch(() => {
            this.listLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancelAdd() {
      this.FormVisible = false
      if (!this.isEdit) {
        for (const index in this.custormGroupForm) {
          this.custormGroupForm[index] = null
        }
      } else {
        this.custormGroupForm = this.copycustormGroupForm
      }
    },
    delCustomGroup(row) {
      this.$confirm(`确定要删除自定义组：${row.group_name} ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delCustomGroupIds.push(row.id)
        this.delCustomGroupsInterim()
      }).catch(() => {
      })
    },
    delCustomGroups() {
      if (this.delCustomGroupIds.length === 0) {
        this.$message({
          message: '请选择需要删除自定义组 ！',
          type: 'error'
        })
        return
      }
      this.$confirm(`确定要批量删除自定义组 ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.delCustomGroupsInterim()
      }).catch(() => {
      })
    },
    delCustomGroupsInterim() {
      this.listLoading = true
      commonApi('/userGroup/remove', 'post', this.delCustomGroupIds).then(response => {
        if (response.code === 1) {
          this.$message({
            message: '自定义组删除完成',
            type: 'success'
          })
          this.listLoading = false
          this.delCustomGroupIds = []
          this.getList()
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    editCustormGroup(row = {}) {
      this.FormVisible = true
      this.isEdit = true
      this.custormGroupForm = { group_id: row.id, group_name: row.group_name, description: row.description }
      this.copycustormGroupForm = row
    },
    confirmEditCustormGroup(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.FormVisible = false
          this.listLoading = true
          commonApi('/userGroup/updateGroup', 'post', this.custormGroupForm).then(response => {
            if (response.code === 1) {
              this.cancelAdd()
              this.listLoading = false
              this.getList()
            }
          }).catch(() => {
            this.listLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleSelectChange(valArr) {
      this.delCustomGroupIds = []
      for (let i = 0; i < valArr.length; i++) {
        this.delCustomGroupIds.push(valArr[i].id)
      }
    },
    tagClose(tag) {
      this.participants = this.participants.filter(par => par !== tag)
    },
    usersChange(row) {
      this.dialogFormVisible = true
      this.customGroupUsersChange.group_id = row.id
      commonApi(`/userGroup/getGroupInfo/${row.id}`, 'get').then(response => {
        if (response.code === 1) {
          this.participants = response.data.users
          this.$nextTick(() => {
            this.setSortParticipants()
          })
        }
      })
    },
    setSortParticipants() {
      const el = document.querySelectorAll('.drag-participants')[0]
      this.sortableParticipant = Sortable.create(el, {
        ghostClass: 'sortableParticipant-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.participants.splice(evt.oldIndex, 1)[0]
          this.participants.splice(evt.newIndex, 0, targetRow)
        }
      })
    },
    confirmUsersChange() {
      for (let i = 0; i < this.participants.length; i++) {
        const isExist = this.customGroupUsersChange.users.some(userId => userId === this.participants[i].id)
        if (!isExist) {
          this.customGroupUsersChange.users.push(this.participants[i].id)
        }
      }
      commonApi('/userGroup/allocation', 'post', this.customGroupUsersChange).then(response => {
        if (response.code === 1) {
          this.customGroupUsersChange.users = []
          this.$message({
            message: '自定义组组员修改成功',
            type: 'success'
          })
        }
      })
      this.dialogFormVisible = false
    },
    cancel() {
      this.dialogFormVisible = false
      this.customGroupUsersChange.users = []
    },
    getCustomGroupUsers(dept) {
      this.searchUsers.data.department = dept
      commonApi('/userGroup/userInfo', 'post', this.searchUsers).then(response => {
        if (response.code === 1) {
          this.users = response.data.rows
        }
        this.loading = false
      })
    }
  }
}
</script>

<style>
  .sortable-ghost{
    opacity: .8;
    color: #fff!important;
    background: #42b983!important;
  }
</style>

<style scoped>
  .icon-star{
    margin-right:2px;
  }
  .drag-handler{
    width: 20px;
    height: 20px;
    cursor: pointer;
  }
  .show-d{
    margin-top: 15px;
  }
  .user-tag{
    margin: 0 10px 10px 0;
  }
</style>
